# -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 15:14:19 2020

@author: 付说举于版筑之间

sort top 3 cars and loop
"""
from oD import od
import copy
from collections import defaultdict
#import pandas as pd
#import matplotlib.pyplot as plt 
from pandas.core.frame import DataFrame
#import numpy as np
'''
a=[1,2,3,4]#列表a
b=[5,6,7,8]#列表b
c={"a" : a,
   "b" : b}#将列表a，b转换成字典
data=DataFrame(c)#将字典转换成为数据框
print(data)
'''

totVeh=9
pltX=[]
pltYs=[]
pltYt=[]
pltDs={}
pltDt={}

for _ in range(8):
    totVeh+=3
    #print('totVeh',totVeh)
    seedNum=0
    for _ in range(1000):
        seedNum+=1
        print('seedNum',seedNum)
        o_d=od(seedNum,totVeh)
        start_list=o_d.getO()
        end_list=o_d.getD()
        #print('fixed_start_list',start_list)
        #print('fixed_end_list',end_list)
        def judgeEx(a, b):  # a和b是两个字符串，这个方程负责比较两个字符串并返回不是0的那个元素的值（不是位置
            for i in range(len(a)):
                if a[i] != b[i]:
                    if a[i] != "0":
                        return a[i]
                    else:
                        return b[i]
        def get_none_zero(a_list):
            not_zero=0
            for i in a_list:
                if i!='0':
                    not_zero+=1
            return not_zero
        
        row=3
        accu_steps=0
        accu_time=0
        bubble_start=start_list[:9]
        bubble_end=end_list[:3]
        loop_time=1
        total_sort=[]
        is_terminal=False
        while True:
            #print('loop_time',loop_time)
            #start_list和end_list是循环嵌套的,初始化！
            
            # 确定一个目标状态（包含bubble_end）产生所有的情况
            per_nums=copy.deepcopy(bubble_start)
            #print('before remove per_nums=',str(per_nums))
            for i in bubble_end:
                per_nums.remove(i)
            #print('after remove per_nums=',str(per_nums))
            final_bubble_end=bubble_end+per_nums
            
            # to face teh corner case like last 6 cars take at most 5 rows
            if len(bubble_start)<=9:
                final_bubble_start=["0","0","0"]+bubble_start+["0","0","0"]
                final_bubble_end=["0","0","0"]+final_bubble_end+["0","0","0"]
            elif len(bubble_start)<=12:
                final_bubble_start=["0","0","0"]+bubble_start
                final_bubble_end=["0","0","0"]+final_bubble_end
            else:
                final_bubble_start=bubble_start
                final_bubble_end=final_bubble_end
            
            #print('final_bubble_end',final_bubble_end)
            # 'final_bubble_start',final_bubble_start
            
            # 引入a star sort并记录返回值，也就是步数
            from oneWay import oneway
            
            ini_astar=oneway(len(final_bubble_start),final_bubble_start,final_bubble_end)
            #steps,time_consuming=None,None
            printL,time_consuming=ini_astar.get_results()
            diPoint = []
            listA = []
        
            s_count = 0
            finalSt = defaultdict(list)
            #print(finalSt.items())
            for i in range(len(printL) - 1):  # 把所有的字符串遍历一下
                listA.append(judgeEx(printL[i].split('.'), printL[i + 1].split('.')))
            #print(listA)
            diPoint.append(listA[0])
            for i in range(0, len(listA)):
                if listA[i] not in diPoint:
                    finalSt[s_count].append(printL[i + 1])
                    diPoint.append(listA[i])
                else:
                    s_count += 1
                    finalSt[s_count].append(printL[i + 1])
                    diPoint.clear()
                    diPoint.append(listA[i])
            
            steps=len(finalSt.items())
            accu_steps+=steps
            accu_time+=time_consuming
            oneway.clear()
            
            # 判停
            if is_terminal==True:  
                #print('accu_steps',accu_steps,'accu_time',accu_time)
                if len(bubble_start)<=12:
                    total_sort+=final_bubble_end[3:9]
                else:
                    total_sort+=final_bubble_end[:6]
                #print('total_sort',total_sort)
                pltX.append(seedNum)
                pltYs.append(accu_steps)
                pltYt.append(accu_time)
                #print('pltX',pltX,'pltYs',pltYs,'pltYt',pltYt)
                
                break
                
            else:
                nine_pos=final_bubble_end[3:-3]
                
                # ,'final_bubble_start,final_bubble_end=',final_bubble_start,final_bubble_end
                # 去掉空行
                count=0
                for i in range(0,3):
                    if nine_pos[3*i]=='0' and nine_pos[3*i+1]=='0' and nine_pos[3*i+2]=='0':
                        count+=1
                        nine_pos=["0","0","0"]+nine_pos[:3*i]+nine_pos[3*i+3:]
                
                last_tail=nine_pos[3*count+3:]
                sort=nine_pos[3*count:3*count+3]
            
            #print("去重之后的小尾巴",last_tail,'count',count)
            #print('nine_pos',nine_pos)
            total_sort+=sort
            
            from tkinter import _flatten
            total_sort=list(_flatten(total_sort))
            #print('total_sort',total_sort)
            '''
            if len(total_sort)==15:
                #print('accu_steps',accu_steps,'accu_time',accu_time)
                total_sort.clear()
            '''
           
            start_list=start_list[9:]
            start_list=last_tail+start_list
            #print('count',count,'start_list',start_list) 
            #print('get_none_zero(start_list)',get_none_zero(start_list))
            # 确定没排好的部分的个数小于6
            if get_none_zero(start_list)==6:
                bubble_start=start_list[:]
                bubble_end=end_list[loop_time*3:loop_time*3+6]
                is_terminal=True
                #print('nex_bubble_start,nex_bubble_end_top6',bubble_start,bubble_end)
            
            # 新的状态就是前9个+后面的切片，loop i第一次是1
            else:
                
                bubble_start=start_list[:9]
                bubble_end=end_list[loop_time*3:loop_time*3+3]
                #print('nex_bubble_start,nex_bubble_end_top3',bubble_start,bubble_end)
                
            loop_time+=1  
    pltDs['{} cars'.format(totVeh)]=pltYs
    pltYs=[]
    pltDt['{} cars'.format(totVeh)]=pltYt
    pltYt=[]

op1233s=DataFrame(pltDs)
op1233t=DataFrame(pltDt)
print('op1233s',op1233s)
print('op1233t',op1233t) 
op1233s.to_csv("op1233s.csv",index=False)
op1233t.to_csv("op1233t.csv",index=False)


''' 
    pd.concat(dataS,DataFrame(pltYs,columns=['车数：{}'.format(totVeh)]))
    pd.concat(dataT,DataFrame(pltYt,columns=['车数：{}'.format(totVeh)]))
dataS.to_csv("test_steps_data.csv")
dataT.to_csv("test_time_data.csv")   
readS = pd.read_csv("test_steps_data.csv")
readT=pd.read_csv("test_time_data.csv")
print('readS',readS,'readT',readT)
'''
'''
figure,axes=plt.subplots() #得到画板、轴
axes.boxplot(pltYt,patch_artist=True) #描点上色
axes.boxplot(pltYs,patch_artist=True) 
plt.show() #展示
'''



